package coursework.senders;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Timer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class Sender extends JFrame{
	
	private boolean active  = true;
	public JTextArea display;
	public static boolean bleeped;
	
	public Sender(long period, int delay) {
		super("Sender");
		bleeped = false;
		setSize(200, 100);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		display = new JTextArea();
		display.setEditable(true);
		getContentPane().add(display);		
		display.append("Bleeped=" + bleeped);
		
		AudioSample sample = AudioSample.getInstance();
		Timer timer = new Timer();
		timer.schedule(sample, 0, period);
		try{
			ServerSocket server = new ServerSocket(7777);
			ExecutorService pool = Executors.newCachedThreadPool();
			while(active){
				Socket client = server.accept();
				SenderTask task = new SenderTask(client, delay, (int)period);
				pool.execute(task);
				Thread.yield();
			}
			pool.shutdown();
			server.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}


	public class AButton extends JButton{

		public AButton(){
			setText("BLEEP!");
			addMouseListener(new MouseListener(){
				public void mouseClicked(MouseEvent arg0) {
					bleep();
				}
				public void mouseEntered(MouseEvent arg0) {
					// TODO Auto-generated method stub
					
				}
				public void mouseExited(MouseEvent arg0) {
					// TODO Auto-generated method stub
					
				}
				public void mousePressed(MouseEvent arg0) {
					// TODO Auto-generated method stub
					
				}
				public void mouseReleased(MouseEvent arg0) {
					// TODO Auto-generated method stub
					
				}
			});
		}
		public void bleep(){
			bleeped = !bleeped;
			display.selectAll();
			display.replaceSelection("");
			display.append("Bleeped=" + bleeped);
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Sender sender = new Sender(1000,0);
	}

}
